import React from 'react'
import {
    View, Text, StyleSheet
} from 'react-native'

export default class FPSTool extends React.Component {

    state = {
        FPS: 60,
        color: 'green'
    }

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return;
        }
    }

    componentDidMount() {
        this.startFPSObserve()
    }

    startFPSObserve() {
        isStart = true

        var rAF = function () {
            return (
                window.requestAnimationFrame || //Chromium  
                window.webkitRequestAnimationFrame || //Webkit 
                window.mozRequestAnimationFrame || //Mozilla Geko 
                window.oRequestAnimationFrame || //Opera Presto 
                window.msRequestAnimationFrame || //IE Trident? 
                function (callback) {
                    window.setTimeout(callback, 1000 / 60);
                }
            );
        }();

        var frame = 0;
        var allFrameCount = 0;
        var lastTime = Date.now();
        var lastFameTime = Date.now();

        var loop = () => {
            var now = Date.now();
            var fs = (now - lastFameTime);
            var fps = Math.round(1000 / fs);

            lastFameTime = now;
            // 不置 0，在动画的开头及结尾记录此值的差值算出 FPS
            allFrameCount++;
            frame++;

            if (now > 1000 + lastTime) {
                var fps = Math.round((frame * 1000) / (now - lastTime));
                if (fps > 60) fps = 60
                var color = ''
                if (fps > 50) {
                    color = 'green'
                } else if (fps > 30) {
                    color = 'yellow'
                } else {
                    color = 'red'
                }
                // console.log(`${new Date()} 1S内 FPS：`, fps);
                this.setState({
                    FPS: fps,
                    color: color
                })
                frame = 0;
                lastTime = now;
            };

            rAF(loop);
        }

        loop();
    }

    render() {
        const { style } = this.props
        return (
            <View style={[styles.container, style]} pointerEvents={"none"}>
                <Text style={{ fontSize: 13 }}>
                    FPS
                </Text>
                <Text style={{ fontSize: 14, color: this.state.color, marginLeft: 5 }}>
                    {this.state.FPS}
                </Text>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: 'rgba(0, 0, 0, 0.1)',
        justifyContent: 'center',
        alignItems: 'center',
        width: 65,
        height: 20,
        left:5,
        borderRadius: 10,
        flexDirection: 'row'
    }
})